"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { useAdminStore } from "@/lib/store"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { ArrowLeft, Plus, Trash2, Grip } from "lucide-react"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { TicketTemplate, TemplateStep } from "@/types/template"
import { 
  DragDropContext, 
  Droppable, 
  Draggable,
  DropResult,
  DroppableProvided,
  DraggableProvided
} from "@hello-pangea/dnd"

export default function EditTemplateClient({ params }: { params: { id: string } }) {
  const router = useRouter()
  const { templates, updateTemplate } = useAdminStore()
  const template = templates.find(t => t.id === params.id)

  const [name, setName] = useState("")
  const [type, setType] = useState("")
  const [description, setDescription] = useState("")
  const [location, setLocation] = useState("")
  const [taskName, setTaskName] = useState("")
  const [target, setTarget] = useState("")
  const [conditions, setConditions] = useState("")
  const [requiredGear, setRequiredGear] = useState("")
  const [precautions, setPrecautions] = useState("")
  const [steps, setSteps] = useState<TemplateStep[]>([])
  
  // 新步骤输入
  const [newStepDescription, setNewStepDescription] = useState("")
  const [newStepIsCritical, setNewStepIsCritical] = useState(false)

  useEffect(() => {
    if (template) {
      setName(template.name)
      setType(template.type)
      setDescription(template.description)
      setLocation(template.location)
      setTaskName(template.task.name)
      setTarget(template.task.target || template.task.name.split(" ")[0] || "")
      setConditions(template.task.conditions)
      setRequiredGear(template.task.requiredGear.join(", "))
      setPrecautions(template.task.precautions.join("\n"))
      setSteps(template.steps || [])
    }
  }, [template])

  if (!template) {
    return <div>模板不存在</div>
  }

  // 处理保存
  const handleSave = () => {
    // 处理任务名称，确保包含目标股道
    const fullTaskName = taskName.includes(target) 
      ? taskName 
      : `${target} ${taskName}`

    const updatedTemplate: Partial<TicketTemplate> = {
      name,
      type,
      description,
      location,
      task: {
        name: fullTaskName,
        target,
        conditions,
        requiredGear: requiredGear.split(",").map(item => item.trim()),
        precautions: precautions.split("\n").map(item => item.trim()).filter(item => item !== ""),
      },
      steps: steps.map((step, index) => ({
        ...step,
        stepNumber: index + 1
      })),
    }

    updateTemplate(params.id, updatedTemplate)
    router.push("/admin/templates")
  }

  // 添加新步骤
  const addStep = () => {
    if (!newStepDescription.trim()) return

    const newStep: TemplateStep = {
      stepNumber: steps.length + 1,
      description: newStepDescription,
      ...(newStepIsCritical && { isCritical: true })
    }

    setSteps([...steps, newStep])
    setNewStepDescription("")
    setNewStepIsCritical(false)
  }

  // 删除步骤
  const deleteStep = (index: number) => {
    const newSteps = [...steps]
    newSteps.splice(index, 1)
    setSteps(newSteps.map((step, idx) => ({ ...step, stepNumber: idx + 1 })))
  }

  // 处理拖放排序
  const handleDragEnd = (result: DropResult) => {
    if (!result.destination) return

    const items = Array.from(steps)
    const [reorderedItem] = items.splice(result.source.index, 1)
    items.splice(result.destination.index, 0, reorderedItem)

    setSteps(items.map((item, index) => ({ ...item, stepNumber: index + 1 })))
  }

  return (
    <div className="container mx-auto py-10 space-y-6">
      <div className="flex items-center">
        <Button variant="outline" size="icon" onClick={() => router.push("/admin/templates")} className="mr-4">
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <h1 className="text-3xl font-bold">编辑操作票模板</h1>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>基本信息</CardTitle>
            <CardDescription>编辑操作票模板的基本信息</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">模板名称</Label>
              <Input 
                id="name" 
                value={name} 
                onChange={(e) => setName(e.target.value)} 
                placeholder="如：隔离开关合闸操作票 (送电) - 标准模板" 
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="type">票种类型</Label>
              <Input 
                id="type" 
                value={type} 
                onChange={(e) => setType(e.target.value)} 
                placeholder="如：隔离开关合闸操作票 (送电)" 
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">模板描述</Label>
              <Textarea 
                id="description" 
                value={description} 
                onChange={(e) => setDescription(e.target.value)} 
                placeholder="输入模板描述" 
                className="resize-none" 
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="location">位置</Label>
              <Input 
                id="location" 
                value={location} 
                onChange={(e) => setLocation(e.target.value)} 
                placeholder="如：丁堰车辆段" 
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>任务信息</CardTitle>
            <CardDescription>编辑操作票的任务相关信息</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="target">目标股道</Label>
                <Input 
                  id="target" 
                  value={target} 
                  onChange={(e) => setTarget(e.target.value)} 
                  placeholder="如：21股道" 
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="taskName">任务名称</Label>
                <Input 
                  id="taskName" 
                  value={taskName} 
                  onChange={(e) => setTaskName(e.target.value)} 
                  placeholder="如：隔离开关送电" 
                />
                <p className="text-xs text-muted-foreground">
                  会自动与目标股道组合，如"21股道 隔离开关送电"
                </p>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="conditions">作业条件</Label>
              <Textarea 
                id="conditions" 
                value={conditions} 
                onChange={(e) => setConditions(e.target.value)} 
                placeholder="输入作业条件" 
                className="resize-none" 
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="requiredGear">必备装备</Label>
              <Input 
                id="requiredGear" 
                value={requiredGear} 
                onChange={(e) => setRequiredGear(e.target.value)} 
                placeholder="用逗号分隔，如：安全帽, 绝缘手套, 绝缘鞋" 
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="precautions">注意事项</Label>
              <Textarea 
                id="precautions" 
                value={precautions} 
                onChange={(e) => setPrecautions(e.target.value)} 
                placeholder="每行一条注意事项" 
                className="resize-none min-h-[100px]" 
              />
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>操作步骤</CardTitle>
          <CardDescription>
            添加和管理操作步骤，可拖动调整顺序
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 步骤列表 */}
          <div className="border rounded-md">
            <DragDropContext onDragEnd={handleDragEnd}>
              <Droppable droppableId="steps">
                {(provided: DroppableProvided) => (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[60px]">序号</TableHead>
                        <TableHead>步骤描述</TableHead>
                        <TableHead className="w-[100px]">关键步骤</TableHead>
                        <TableHead className="w-[80px]">操作</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody {...provided.droppableProps} ref={provided.innerRef}>
                      {steps.map((step, index) => (
                        <Draggable key={index} draggableId={`step-${index}`} index={index}>
                          {(provided: DraggableProvided) => (
                            <TableRow 
                              ref={provided.innerRef}
                              {...provided.draggableProps}
                            >
                              <TableCell className="font-medium">
                                <div className="flex items-center">
                                  <div 
                                    {...provided.dragHandleProps}
                                    className="mr-2 cursor-grab"
                                  >
                                    <Grip className="h-4 w-4" />
                                  </div>
                                  {step.stepNumber}
                                </div>
                              </TableCell>
                              <TableCell>{step.description}</TableCell>
                              <TableCell className="text-center">
                                {step.isCritical ? "是" : "否"}
                              </TableCell>
                              <TableCell>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => deleteStep(index)}
                                >
                                  <Trash2 className="h-4 w-4 text-red-500" />
                                </Button>
                              </TableCell>
                            </TableRow>
                          )}
                        </Draggable>
                      ))}
                      {provided.placeholder}
                    </TableBody>
                  </Table>
                )}
              </Droppable>
            </DragDropContext>
          </div>

          {/* 添加步骤 */}
          <div className="flex items-end gap-2">
            <div className="flex-1">
              <Label htmlFor="stepDescription">步骤描述</Label>
              <Input
                id="stepDescription"
                value={newStepDescription}
                onChange={(e) => setNewStepDescription(e.target.value)}
                placeholder="输入步骤描述"
              />
            </div>
            <div className="w-[120px] flex flex-col">
              <Label htmlFor="isCritical" className="mb-2">关键步骤</Label>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="isCritical"
                  checked={newStepIsCritical}
                  onCheckedChange={(checked) => setNewStepIsCritical(!!checked)}
                />
                <Label htmlFor="isCritical" className="text-sm font-normal">是</Label>
              </div>
            </div>
            <Button type="button" onClick={addStep}>
              <Plus className="h-4 w-4 mr-1" /> 添加
            </Button>
          </div>
        </CardContent>
        <CardFooter className="flex justify-end space-x-2">
          <Button variant="outline" onClick={() => router.push("/admin/templates")}>
            取消
          </Button>
          <Button onClick={handleSave}>保存</Button>
        </CardFooter>
      </Card>
    </div>
  )
} 